package com.mchsdk.paysdk.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.mchsdk.open.GPExitResult;
import com.mchsdk.open.MCApiFactory;
import com.mchsdk.paysdk.bean.OffLineAnnounceModel;
import com.mchsdk.paysdk.bean.PersonalCenterModel;
import com.mchsdk.paysdk.bean.UserReLogin;
import com.mchsdk.paysdk.bean.UserReLogin.ReLoginCallback;
import com.mchsdk.paysdk.common.Constant;
import com.mchsdk.paysdk.dialog.MCTipDialog;
import com.mchsdk.paysdk.entity.ChannelAndGameinfo;
import com.mchsdk.paysdk.http.process.UpdateNikeNameProcess;
import com.mchsdk.paysdk.http.process.UserInfoProcess;
import com.mchsdk.paysdk.utils.MCLog;
import com.mchsdk.paysdk.utils.ToastUtil;

public class MCPersonalInfoActivity extends MCBaseActivity {

	/**
	 * 日志打印
	 */
	private final static String TAG = "MCPersonalInfoActivity";

	/**
	 * 显示用户昵称部分
	 */
	RelativeLayout rlCurrentNike;

	/**
	 * 修改用户昵称部分
	 */
	RelativeLayout rlUpdateNike;

	/**
	 * 昵称输入框
	 */
	EditText etUpdateNike;

	/**
	 * 昵称
	 */
	TextView txtNike;

	/**
	 * 用户名
	 */
	TextView txtAccount;

	/**
	 * 平台币余额
	 */
	TextView txtPtbMoney;

	/**
	 * 绑定手机状态
	 */
	TextView txtBindPhoneState;

	/**
	 * 绑定平台币余额
	 */
	TextView txtBindPtbMoney;

	/**
	 * 修改密码
	 */
	RelativeLayout rlUpdatePwd;
	View lineUpdatePwd;
	/**
	 * 修改游客信息
	 */
	RelativeLayout rlUpdateVisitorinfo;
	View lineSetVisitorInfo;

	/**
	 * 绑定手机号
	 */
	RelativeLayout rlBindPhone;
	View lineBindphone;
	/**
	 * 实名认证
	 */
	RelativeLayout rlAuthentication;
	TextView textAuthentication;
	private int type = 1;//标识是否实名认证 -1 该用户ID不存在 0该用户身份未审核 1 该用户身份审核未通过 2该用户身份审核通过成年 3该用户身份审核通过未成年
	/**
	 * 退出登录
	 */
	Button btn_perifo_ext;
	/**
	 * 键盘控制
	 */
	InputMethodManager imm;

	/**
	 * 用户名
	 */
	private String account;

	/**
	 * 昵称
	 */
	String nickName;

	MCTipDialog nickTip;

	/**
	 * 绑定手机号
	 */
	private final int requestBindPhone = 10;

	/**
	 * 绑定手机号
	 */
	private final int updatePassword = 11;

	/**
	 * 平台币充值
	 */
	private final int adduserptb = 12;
	/**
	 * 身份证号  姓名
	 */
	private String real_name;
	private String idcard;
	private Handler mHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (null != infoTip) {
				try {
					infoTip.dismiss();
					infoTip = null;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			try {
				if (null != nickTip) {
					nickTip.dismiss();
					nickTip = null;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			switch (msg.what) {
				case Constant.GET_USER_INFO_SUCCESS :// 获取用户信息
					ChannelAndGameinfo info = (ChannelAndGameinfo) msg.obj;
					if (null != info) {
						handlerUserInfo(info);
					} else {
						Toast.makeText(getApplicationContext(), "请重新登录", Toast.LENGTH_SHORT).show();
						finish();
					}
					break;
				case Constant.GET_USER_INFO_FAIL :
					String tip = (String) msg.obj;
					Toast.makeText(getApplicationContext(), tip, Toast.LENGTH_SHORT).show();
					finish();
					break;
				case Constant.UPDATE_NIKE_SUCCESS :
					handlerNikeName();
					break;
				case Constant.UPDATE_NIKE_FAIL :
					String res = (String) msg.obj;
					if (TextUtils.isEmpty(res)) {
						res = "网络异常";
					}
					Toast.makeText(getApplicationContext(), res, Toast.LENGTH_SHORT).show();
					break;
				default :
					break;
			}
		}
	};
//提示对话框
	private MCTipDialog infoTip;
	private Button id_test;
	private String age_status;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN | WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED);
		setContentView(getLayout("activity_mch_personal_info"));
		initView();
	}

	@Override
	protected void onResume() {
		super.onResume();
		initData();
	}

	protected void handlerNikeName() {
		if (!TextUtils.isEmpty(nickName)) {
			txtNike.setText(nickName);
			etUpdateNike.setText("");

			rlCurrentNike.setVisibility(View.VISIBLE);
			rlUpdateNike.setVisibility(View.GONE);
		}
	}

	/**
	 * 获取用户的信息显示在个人中心的页面上
	 * @param info
	 */
	protected void handlerUserInfo(ChannelAndGameinfo info) {
		PersonalCenterModel.getInstance().channelAndGame.setNikeName(info.getNikeName());
		PersonalCenterModel.getInstance().channelAndGame.setPlatformMoney(info.getPlatformMoney());
		PersonalCenterModel.getInstance().channelAndGame.setPhoneNumber(info.getPhoneNumber());
		PersonalCenterModel.getInstance().channelAndGame.setBindPtbMoney(info.getBindPtbMoney());
		PersonalCenterModel.getInstance().channelAndGame.setAge_status(info.getAge_status());
		PersonalCenterModel.getInstance().channelAndGame.setIdcard(info.getIdcard());
		PersonalCenterModel.getInstance().channelAndGame.setReal_name(info.getReal_name());
		age_status = info.getAge_status();
		txtAccount.setText("账号："+account);
		String nick = info.getNikeName();
		if (TextUtils.isEmpty(nick)) {
			nick = "梦创sdk";
		}
		txtNike.setText(nick);
		txtPtbMoney.setText(String.format("%.2f", info.getPlatformMoney()));
		txtBindPtbMoney.setText(String.format("%.2f", info.getBindPtbMoney()));

		checkUserRegisterType(info.getUserRegisteType());
		isCertificate();
		isBindPhone();
	}

	/**
	 * 0游客 1帐号 2手机 3微信 4QQ 5百度 6微博
	 * @param registeType 用户注册类型
     */
	private void checkUserRegisterType(int registeType){
		MCLog.w(TAG, "registeType:" + registeType);
		rlUpdatePwd.setVisibility(View.GONE);
		lineUpdatePwd.setVisibility(View.GONE);
		rlBindPhone.setVisibility(View.GONE);
		lineBindphone.setVisibility(View.GONE);
		rlUpdateVisitorinfo.setVisibility(View.GONE);
		lineSetVisitorInfo.setVisibility(View.GONE);
		switch (registeType){
			case 0:
//				rlBindPhone.setVisibility(View.VISIBLE);
				lineBindphone.setVisibility(View.VISIBLE);
				rlUpdateVisitorinfo.setVisibility(View.VISIBLE);
				lineSetVisitorInfo.setVisibility(View.VISIBLE);
				break;
			case 1:
			case 2:
				rlUpdatePwd.setVisibility(View.VISIBLE);
				lineUpdatePwd.setVisibility(View.VISIBLE);
				rlBindPhone.setVisibility(View.VISIBLE);
				lineBindphone.setVisibility(View.VISIBLE);
				break;
			default:
				break;
		}
	}

	/**
	 * 是否绑定手机号
	 */
	private void isBindPhone() {
		if (TextUtils.isEmpty(PersonalCenterModel.getInstance().getPhone())) {
			txtBindPhoneState.setText("未设置");
		} else {
			txtBindPhoneState.setText("已设置");
		}
	}

	/**
	 * 是否实名认证
	 */
	private void isCertificate() {
		if (age_status.equals("2")){
			type = 2;
			textAuthentication.setText("已认证");
//			new OffLineAnnounceModel(MCPersonalInfoActivity.this).closeAntiAddiction();
			MCApiFactory.getMCApi().offLineAnnounce(MCPersonalInfoActivity.this);
		}
		else if (age_status.equals("0")){
			type = 0;
			textAuthentication.setText("未认证");
		}
		else if (age_status.equals("1")){
			type = 1;
			textAuthentication.setText("未通过");
		}
		else if (age_status.equals("3")){
			type = 3;//已认证未满18周岁
			textAuthentication.setText("已认证");
		}
		else if (age_status.equals("4")){
			type = 4;
			textAuthentication.setText("审核中");
		}
	}
	private void initData() {
		if (TextUtils.isEmpty(PersonalCenterModel.getInstance().getUserId())) {
			UserReLogin reLogin = new UserReLogin(MCPersonalInfoActivity.this);
			reLogin.userToLogin(new ReLoginCallback() {

				@Override
				public void reLoginResult(boolean res) {
					if (res) {
						quereUserInfo();
					} else {
						Toast.makeText(MCPersonalInfoActivity.this, "获取个人信息失败,请登录", Toast.LENGTH_SHORT).show();
						finish();
					}
				}
			});
			return;
		}
		quereUserInfo();
	}

	private void quereUserInfo() {
		account = PersonalCenterModel.getInstance().channelAndGame.getAccount();
		infoTip = new MCTipDialog.Builder().setMessage("").show(this, this.getFragmentManager());
		UserInfoProcess userInfoProcess = new UserInfoProcess();
		userInfoProcess.setType("0");
		userInfoProcess.setAccount("");
		userInfoProcess.post(mHandler);
	}

	private void initView() {
		imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

		TextView txtTitle = (TextView) findViewById(getId("tv_mch_header_title"));
		txtTitle.setText("个人中心");
		ImageView ivBack = (ImageView) findViewById(getId("iv_mch_header_back"));
		ivBack.setVisibility(View.VISIBLE);
		ivBack.setOnClickListener(backClick);
		ImageView ivClose = (ImageView) findViewById(getId("iv_mch_header_close"));
		ivClose.setVisibility(View.GONE);
		txtBindPhoneState = (TextView) findViewById(getId("txt_bind_phone_state"));
		rlCurrentNike = (RelativeLayout) findViewById(getId("rl_mch_current_nike"));
		rlCurrentNike.setVisibility(View.VISIBLE);
		etUpdateNike = (EditText) findViewById(getId("et_mch_update_nike"));
		txtNike = (TextView) findViewById(getId("txt_mch_nike_name"));
		txtAccount = (TextView) findViewById(getId("txt_mch_float_account"));
		txtPtbMoney = (TextView) findViewById(getId("txt_ptb_money"));
		txtBindPtbMoney = (TextView) findViewById(getId("txt_bind_ptb_money"));
		btn_perifo_ext = (Button) findViewById(getId("btn_perifo_ext"));
		btn_perifo_ext.setOnClickListener(extlis);
		ImageView ivNike = (ImageView) findViewById(getId("iv_mch_nike_name"));
		ivNike.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				MCLog.w(TAG, "#txtNike onClick");
				// etUpdateNike.setFocusable(true);
				// etUpdateNike.setFocusableInTouchMode(true);
				etUpdateNike.setText("");
				etUpdateNike.requestFocus();
				rlCurrentNike.setVisibility(View.GONE);
				rlUpdateNike.setVisibility(View.VISIBLE);
			}
		});

		rlUpdateNike = (RelativeLayout) findViewById(getId("rl_mch_update_nike"));
		rlUpdateNike.setVisibility(View.GONE);
		TextView txtUpdateNike = (TextView) findViewById(getId("txt_mch_update_nike"));
		txtUpdateNike.setOnClickListener(updateNikeClick);
//         RelativeLayout rl_mch_ptb=(RelativeLayout)findViewById(getId("rl_mch_ptb"));
//         rl_mch_ptb.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				String msg = "平台币可以在平台任意游戏使用";
//				ToastUtil.show(getApplicationContext(), msg);
//			}
//		});
//         RelativeLayout rl_mch_bind_ptb=(RelativeLayout)findViewById(getId("rl_mch_bind_ptb"));
//         rl_mch_bind_ptb.setOnClickListener(new OnClickListener() {
//
//			@Override
//			public void onClick(View v) {
//				String msg = "绑定平台币只能在当前游戏中使用";
//				ToastUtil.show(getApplicationContext(), msg);
//			}
//		});
       //修改密码
		rlUpdatePwd = (RelativeLayout) findViewById(getId("rl_mch_update_pwd"));
		lineUpdatePwd = (View) findViewById(getId("line_mch_updatepwd"));
		rlUpdatePwd.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				PersonalCenterModel.getInstance().setUpdatePwd(false);
				Intent updatePwd = new Intent(MCPersonalInfoActivity.this, MCChangePasswordActivity.class);
				startActivity(updatePwd);
				// startActivityForResult(updatePwd, updatePassword);
			}
		});
         //设置用户名rl_mch_update_visitorinfo
		rlUpdateVisitorinfo = (RelativeLayout) findViewById(getId("rl_mch_update_visitorinfo"));
		lineSetVisitorInfo = (View) findViewById(getId("line_mch_setusername"));
		rlUpdateVisitorinfo.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent updatevisitorinfo = new Intent(MCPersonalInfoActivity.this, MCVisitorUpdateInfo.class);
				startActivity(updatevisitorinfo);
			}
		});
        //绑定手机
		rlBindPhone = (RelativeLayout) findViewById(getId("rl_mch_bind_phone"));
		lineBindphone = (View) findViewById(getId("line_mch_bindphone"));
		rlBindPhone.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent bindphone = new Intent(MCPersonalInfoActivity.this, MCBindPhoneActivity.class);
				// startActivity(bindphone);
				//startActivityForResult(Intent intent, int requestCode)
				startActivityForResult(bindphone, requestBindPhone);
			}
		});
        //实名认证
		rlAuthentication = (RelativeLayout) findViewById(getId("rl_mch_real_name_authentication"));
		textAuthentication = (TextView) findViewById(getId("txt_mch_real_name_authentication"));
		rlAuthentication.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent authentication  = new Intent(MCPersonalInfoActivity.this, ToCertificateActivity.class);
				if (type == 2) {
					authentication.putExtra("type", "2");
					startActivity(authentication);
//					ToastUtil.show(MCPersonalInfoActivity.this,"已经实名认证了");
				}
				else if (type == 0 ){
					authentication.putExtra("type","0");
					startActivity(authentication);
				}
				else if (type == 1 ){
					authentication.putExtra("type","1");
					startActivity(authentication);
				}
				else if (type == 3 ){
					 authentication.putExtra("type","2");
						startActivity(authentication);
				}
				else if (type == 4 ){
					authentication.putExtra("type","0");
					startActivity(authentication);
				}

//标识是否实名认证 -1 该用户ID不存在 0该用户身份未审核 1 该用户身份审核未通过 2该用户身份审核通过成年 3该用户身份审核通过未成年
			}
		});
		// 充值记录
		RelativeLayout rlMoneyRecord = (RelativeLayout) findViewById(getId("rl_mch_money_record"));
		rlMoneyRecord.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent record = new Intent(MCPersonalInfoActivity.this, MCMoneyRecordActivity.class);
				startActivity(record);
			}
		});

		// 平台币充值
		RelativeLayout rlAddPtb = (RelativeLayout) findViewById(getId("rl_mch_add_ptb"));
		rlAddPtb.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent record = new Intent(MCPersonalInfoActivity.this, MCAddPtbMoneyActivity.class);
				startActivityForResult(record, adduserptb);
			}
		});
	}



	/**
	 * 修改昵称的监听事件
	 */
	OnClickListener updateNikeClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			imm.hideSoftInputFromWindow(etUpdateNike.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
			nickName = etUpdateNike.getText().toString().trim();
			if (TextUtils.isEmpty(nickName)) {
				Toast.makeText(getApplicationContext(), "请输入昵称", Toast.LENGTH_SHORT).show();
				rlCurrentNike.setVisibility(View.VISIBLE);
				rlUpdateNike.setVisibility(View.GONE);
				return;
			}
			nickTip = new MCTipDialog.Builder().setMessage("正在修改昵称").show(MCPersonalInfoActivity.this, getFragmentManager());

			UpdateNikeNameProcess updateNickPreocess = new UpdateNikeNameProcess();
			updateNickPreocess.setNikeName(nickName);
			updateNickPreocess.setCode("nickname");
			updateNickPreocess.post(mHandler);
		}
	};
	/**
	 * 监听返回的事件
	 */
	OnClickListener backClick = new OnClickListener() {

		@Override
		public void onClick(View v) {
			finish();
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		// 绑定手机号
		if (requestBindPhone == requestCode) {
			if (!TextUtils.isEmpty(PersonalCenterModel.getInstance().getPhone())) {
				isBindPhone();
			}
		}
		// 修改密码
		if (updatePassword == requestCode) {
			// if(PersonalCenterModel.getInstance().isUpdatePwd()){
			// MCApiFactory.getMCApi().startlogin(getApplicationContext(),
			// null);
			// finish();
			// }
		}
		// 平台币充值
		if (adduserptb == requestCode) {
			txtPtbMoney.setText(PersonalCenterModel.getInstance().getUserPtb());
		}
	}


	OnClickListener extlis = new OnClickListener() {

		@Override
		public void onClick(View v) {
			if (null != MCApiFactory.getMCApi().getExitFromPersonInfo()) {
				MCApiFactory.getMCApi().stopFloating(MCPersonalInfoActivity.this);
				GPExitResult exit = new GPExitResult();
				exit.mResultCode = GPExitResult.GPSDKResultCodeOfPersonInfo;
				MCApiFactory.getMCApi().getExitFromPersonInfo().onExitFinish(exit);
			}
			if (null != MCApiFactory.getMCApi().getLoginClass()) {
				Class<?> clazz = MCApiFactory.getMCApi().getLoginClass();
				Intent exitIntent = new Intent(MCPersonalInfoActivity.this, clazz);
				startActivity(exitIntent);
			}
			finish();
		}
	};
}
